#!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime
from typing import TypeVar

from sqlalchemy import or_, and_
from sqlalchemy.orm import Session

from app.common.page import PageParam
from app.models import User
from pydantic import BaseModel

from app.dao.base_dao import BaseDao
from app.db.base_class import Base
from app.models.bar import Bar
from app.models.constant import Constant
from app.models.favorite import Favorite
from app.models.instrument import Instrument
from app.models.picker import Picker
from app.models.picker_instrument import PickerInstrument
from app.models.strategy import Strategy
from app.models.user_setting import UserSetting
from app.schemas.bar import CandlestickQuery


class PickerDao(BaseDao[Picker]):
    def __init__(self):
        super(PickerDao, self).__init__()
        self.modelClass = Picker
        self.id = Picker.id

    def reset(self, db, id, total=0):
        picker = pickerDao.selectById(db, id)
        picker.filterCount = 0
        picker.total = total
        picker.pickCount = 0
        picker.startDate = datetime.now()
        picker.endDate = None

    def updatePickResult(self, db, id, picked):
        updateObj = {
            'filterCount': Picker.filterCount + 1
        }
        if picked:
            updateObj['pickCount'] = Picker.pickCount + 1
        db.query(Picker).filter(Picker.id == id).update(updateObj)
        picker = self.selectById(db, id)
        if picker.filterCount == picker.total:
            picker.endDate = datetime.now()

    def selectPickedInstruments(self, db: Session, queryWrapper: CandlestickQuery):
        result = db.query(Instrument.id, Favorite.id.label('favoriteId'), Instrument.name, Instrument.symbol, Bar.close, Bar.open, Bar.low, Bar.high,
                          Bar.volume, Bar.amount, Bar.barDate, Bar.preClose, Bar.change,Instrument.precision) \
            .select_from(PickerInstrument) \
            .outerjoin(Favorite, and_(PickerInstrument.instrumentId == Favorite.instrumentId,
                                      Favorite.userId == queryWrapper.userId,
                                      PickerInstrument.pickerId == queryWrapper.pickerId)) \
            .outerjoin(Instrument, PickerInstrument.instrumentId == Instrument.id) \
            .outerjoin(Bar, and_(PickerInstrument.instrumentId == Bar.instrumentId,
                                 Bar.barDate == queryWrapper.barDate,
                                 Bar.frequency == queryWrapper.frequency,
                                 Bar.adjustFlag == queryWrapper.adjust)) \
            .filter(
            PickerInstrument.pickerId == queryWrapper.pickerId,
            Instrument.marketType == queryWrapper.marketType) \
            .order_by(Instrument.symbol.asc()) \
            .all()
        return result



pickerDao = PickerDao()
